import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/edit_text_field.dart';
import 'package:qunaimedical/components/item_add.dart';
import 'package:qunaimedical/components/item_image_preview.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/consultation.dart';
import 'package:qunaimedical/pages/conversations/custom_video_player.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

/// 即时咨询创建
class TimelyConsultationAddPage extends StatefulWidget {
  const TimelyConsultationAddPage({Key key}) : super(key: key);

  @override
  _TimelyConsultationAddPageState createState() =>
      _TimelyConsultationAddPageState();
}

class _TimelyConsultationAddPageState extends State<TimelyConsultationAddPage> {
  static String _tag = '_TimelyConsultationAddPageState';
  final _picker = ImagePicker();

  /// 选中的图片
  List<Asset> _images = <Asset>[];

  /// 用户上传的图片路径
  List<String> _uploadedImages = [];
  List<String> _uploadedVideos = [];

  /// 最多选9张图片
  int maxImageCount = 9;

  PickedFile _video;

  /// 视频缩略图
  GenThumbnailImage _futureImage;

  TextEditingController _themeController = TextEditingController();
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _themeController.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('创建咨询'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: ListView(
              padding: EdgeInsets.only(top: 10),
              children: [
                PrimaryLabel('主题'),
                EditTextField(
                  maxLines: 5,
                  maxLength: 400,
                  hintText: '请输入您的主题',
                  controller: _themeController,
                ),
                CustomDivider(),
                PrimaryLabel('咨询内容'),
                EditTextField(
                  maxLines: 5,
                  maxLength: 500,
                  hintText: '请输入咨询内容',
                  controller: _controller,
                ),
                CustomDivider(),
                PrimaryLabel(
                  '上传图片',
                  trailing: Text('${_images.length}/$maxImageCount'),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                  child: Text(
                    '上传相关图片（检查单、CT、病例、患处、药品等）。',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                Container(
                  color: Colors.white,
                  height: 110,
                  width: double.maxFinite,
                  alignment: Alignment.topLeft,
                  padding: EdgeInsets.all(10),
                  child: ListView.separated(
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (c, i) {
                      if (i == _images.length) {
                        return ItemAdd(onTap: _selectImages);
                      } else {
                        return InkWell(
                          onTap: () {
                            CommonUtils.openGallery(
                                context,
                                _uploadedImages
                                    .map((e) => Urls.BASE_URL + e)
                                    .toList(),
                                i);
                          },
                          child: ItemImagePreview(
                            _images[i],
                            onTap: () {
                              // 删除图片时，判断已上传图片列表中是否包含这张照片。
                              if (_uploadedImages.length > i) {
                                _uploadedImages.removeAt(i);
                              }
                              setState(() {
                                _images.removeAt(i);
                              });
                            },
                          ),
                        );
                      }
                    },
                    itemCount: _images.length == maxImageCount
                        ? _images.length
                        : _images.length + 1,
                    padding: EdgeInsets.only(left: 0),
                    separatorBuilder: (BuildContext context, int index) {
                      // 给最后一个加号前面添加间距。
                      return SizedBox(
                        width: _images.length > 0 && index == _images.length - 1
                            ? 13
                            : 0,
                      );
                    },
                  ),
                ),
                CustomDivider(),
                PrimaryLabel('上传视频'),
                Container(
                  height: 100,
                  color: Colors.white,
                  padding: EdgeInsets.all(10),
                  alignment: Alignment.centerLeft,
                  child: _video == null
                      ? ItemAdd(onTap: _selectVideo)
                      : Stack(
                          children: [
                            Container(
                              child: InkWell(
                                child: ClipRRect(
                                  child: _futureImage,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(6)),
                                ),
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (c) => CustomVideoPlayer(
                                        _video.path,
                                        isLocalFile: true,
                                      ),
                                    ),
                                  );
                                },
                              ),
                              margin: EdgeInsets.all(5),
                            ),
                            Positioned(
                              right: 0,
                              top: 0,
                              child: InkWell(
                                child: Image.asset(
                                  'assets/images/ic_delete.png',
                                  width: 18,
                                  height: 18,
                                ),
                                onTap: () {
                                  setState(() {
                                    _video = null;
                                    _uploadedVideos.clear();
                                  });
                                },
                              ),
                            )
                          ],
                        ),
                ),
              ],
            ),
          ),
          PrimaryButton(
            '提交',
            onPressed: _create,
          ),
        ],
      ),
    );
  }

  /// 选择视频
  void _selectVideo() async {
    CommonUtils.hideKeyboard(context);
    showDialog(
        context: context,
        builder: (c) {
          return SimpleDialog(
            title: Text('上传视频'),
            children: [
              SimpleDialogOption(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text('从相册选取'),
                ),
                onPressed: () => _selectVideoFromGallery(0),
              ),
              SimpleDialogOption(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text('使用相机拍摄'),
                ),
                onPressed: () => _selectVideoFromGallery(1),
              ),
            ],
          );
        });
  }

  void _selectVideoFromGallery(int index) async {
    Navigator.pop(context);
    if (await Permission.camera.request().isGranted) {
      var data = await _picker.getVideo(
        source: index == 0 ? ImageSource.gallery : ImageSource.camera,
        maxDuration: Duration(seconds: 30),
      );
      if (mounted) {
        setState(() {
          _video = data;
          _futureImage = GenThumbnailImage(
              thumbnailRequest: ThumbnailRequest(
                  video: _video.path,
                  thumbnailPath: null,
                  imageFormat: ImageFormat.JPEG,
                  maxHeight: 200,
                  maxWidth: 200,
                  timeMs: 0,
                  quality: 50));
          if (_video != null) {
            _uploadVideos();
          }
        });
      }
      Log.d(_tag, '${_video?.path}');
    } else {
      openAppSettings();
    }
  }

  /// 视频上传
  void _uploadVideos() async {
    DialogUtils.showWaitDialog(context);
    FormData formData = FormData.fromMap({});
    formData.files.addAll((await CommonUtils.files2MapEntry([_video])));
    var value = await XHttp.uploadFiles(
      Urls.UPLOAD,
      formData,
    );
    if (value != null) {
      ListResponse response = ListResponse.fromJson(value);
      if (response.code == 1) {
        _uploadedVideos = List<String>.from(response.data);
      }
    }
    Navigator.pop(context);
  }

  void _selectImages() async {
    CommonUtils.hideKeyboard(context);
    try {
      List<Asset> value = await MultiImagePicker.pickImages(
        maxImages: maxImageCount,
        selectedAssets: _images,
      );
      if (mounted) {
        setState(() {
          _images = value;
        });
        if (_images.isNotEmpty) {
          _uploadImages();
        }
      }
    } on Exception catch (e) {
      Log.d(_tag, e);
    }
  }

  /// 图片上传
  void _uploadImages() async {
    DialogUtils.showWaitDialog(context);
    FormData formData = FormData.fromMap({});
    formData.files.addAll((await CommonUtils.images2MapEntry(_images)));
    var value = await XHttp.uploadFiles(
      Urls.UPLOAD,
      formData,
    );
    if (value != null) {
      ListResponse response = ListResponse.fromJson(value);
      if (response.code == 1) {
        _uploadedImages = List<String>.from(response.data);
      }
    }
    Navigator.pop(context);
  }

  /// 创建订单
  void _create() async {
    var user = SPUtils.getUser();
    if (user == null) {
      Log.i('no user info, please login.');
      return;
    }
    if (_themeController.text.trim().isEmpty) {
      ToastUtil.show('请输入主题', context);
      return;
    }
    if (_controller.text.trim().isEmpty) {
      ToastUtil.show('请输入咨询内容', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var params = {
      "doctorId": SPUtils.getUser().id, //医生账号id
      "content": _controller.text.trim(), //主诉
      "appointmentImag": _uploadedImages.join(','), //图片
      "title": _themeController.text.trim(),
      "video": "shipin", //视频
      "appType": "doctor" //app端
    };
    if (_uploadedVideos.isNotEmpty) {
      params['video'] = _uploadedVideos.first;
    }
    var data = await XHttp.postJson(Urls.TIMELY_CONSULTATION_ADD, params);
    Navigator.pop(context);
    if (data != null) {
      Map<String, dynamic> response = data as Map<String, dynamic>;
      if (response['code'] == 1) {
        // 订单创建成功，返回首页。
        DialogUtils.showAlertDialog(context, '提示', '提交成功！', onPressed: () {
          Navigator.pop(context);
          Navigator.pop(context, true);
        });
      }
    }
  }
}
